
use bevy::prelude::*;

use crate::ui::PieceId;
use crate::chess::board::Chessboard;
use crate::chess::{PointState, PieceColor};

pub fn piece_click_system(
    asset: Res<AssetServer>,
    mut board: ResMut<Chessboard>,
    mut query: Query<(&Interaction, &PieceId, &mut UiImage, &mut UiColor), (Changed<Interaction>, With<Button>)>,
) {
    // let black: UiImage = asset.load("black.png").into();
    // let white: UiImage = asset.load("white.png").into();
    for (interaction, id, mut image, mut color) in query.iter_mut() {
        match *interaction {
            Interaction::Clicked => {
                info!("id: {:?}", id.id);
                // info!("color {:?}", color);
                // *image = black.clone()
                board.update(id.id);
            }
            Interaction::Hovered => {
                // *color = Color::rgb(0.0, 0.98, 0.0).into();
                // *image = UiImage::default()
            }
            Interaction::None => {
                // *image = white.clone()
                // *color = Color::rgb(1.0, 1.0, 1.0).into();
                // *color = Color::rgb(0.0, 0.98, 0.0).into();
                // *image = UiImage::default()
            }
        }
    }
}

pub fn board_update_system(
    asset: Res<AssetServer>,
    board: Res<Chessboard>,
    mut query: Query<(&PieceId, &mut UiImage), With<Button>>,
) {
    let black: UiImage = asset.load("black.png").into();
    let white: UiImage = asset.load("white.png").into();
    let empty: UiImage = asset.load("empty.png").into();
    let kill: UiImage = asset.load("kill.png").into();
    for (id, mut image) in query.iter_mut() {
        let state = board.point_state(id.id);
        match state {
            None => *image = empty.clone().into(),
            Some(point) => {
                match point {
                    PointState::Kill => *image = kill.clone().into(),
                    PointState::Piece(color) => {
                        match color {
                            PieceColor::White => *image = white.clone().into(),
                            PieceColor::Black => *image = black.clone().into(),
                        }
                    }
                }
            }
        }
    }
}